-module(tmnesia).
-compile(export_all).

-record(person, {
        name,
        sex,
        age
    }).

test(Type) ->
    case erlang:is_alive() of
        false ->
            net_kernel:start([foo, shortnames]);
        true ->
            ok
    end,
    mnesia:delete_schema([node()]),
    mnesia:create_schema([node()]),
    mnesia:start(),
    case Type of
        ram_copies ->
            ok;
        disc_copies ->
            io:format("make sure .....~n"),
            makesure_use_dir()
    end,

    {atomic, ok} = mnesia:create_table(person, [
                                %{index, [#person.sex]},
                                {Type, [node()]},
                                {attributes, record_info(fields, person)},
                                {load_order, 1},
                                {type, set}
                            ]),

    [begin P = #person{name = N, sex = N rem 2, age = random:uniform(100)}, 
            mnesia:dirty_write(P)
    end
    || N <- lists:seq(1, 200000)],

    {T1, V1} = timer:tc(?MODULE, read_name, []),
    ST1 = lists:concat(["read the name : ", T1]),
    {T2, V2} = timer:tc(?MODULE, read_age, []),
    ST2 = lists:concat(["read the age :", T2]),

    mnesia:add_table_index(person, age),

    {T3, V3} = timer:tc(?MODULE, read_name, []),
    ST3 = lists:concat(["after index for age,read the name :", T3]),
    {T4, V4} = timer:tc(?MODULE, read_age, []),
    ST4 = lists:concat(["after index for age, read the age :", T4]),
    {T5, V5} = timer:tc(?MODULE, read_age_index, []),
    ST5 = lists:concat(["after index for age,read the age index:", T5]),
    io:format("~p~n~p~n~p~n~p~n~p~n", [ST1, ST2, ST3, ST4, ST5]).

read_name() ->
    mnesia:dirty_read(person, 10000).

read_age() ->
    mnesia:dirty_match_object(#person{age = 41, _='_'}).

read_age_index() ->
    mnesia:dirty_index_read(person, 41, #person.age).


makesure_use_dir() ->
    case mnesia:table_info(schema, storage_type) of
        ram_copies ->
            mnesia:change_table_copy_type(schema, node(), disc_copies);
        disc_copies ->
            ok
    end.
